using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Practices.ObjectBuilder2;
using Debug=System.Diagnostics.Debug;

namespace Common.Unity.Extensions.PropertyMapper
{
	public static class PropertyMappingKeyHelper
	{
		readonly static Dictionary<PropertyMappingKey,IEnumerable<PropertyMappingKey>> cache = new Dictionary<PropertyMappingKey, IEnumerable<PropertyMappingKey>>();

		public static IEnumerable<PropertyMappingKey> ResolveHierarchy( PropertyMappingKey key )
		{
			lock ( cache )
			{
				if ( !cache.ContainsKey( key ) )
				{
					cache.Add( key, CreateHierarchy( key ).ToArray() );
				}
				return cache[key];
			}
		}

		static IEnumerable<PropertyMappingKey> CreateHierarchy( PropertyMappingKey key )
		{
			Type source = key.Source;
			while ( source != null )
			{
				Type type = key.TargetBuildKey.Type;
				while ( type != null )
				{
					yield return new PropertyMappingKey( source, new NamedTypeBuildKey( type, key.TargetBuildKey.Name ) );
					type = type.BaseType;
				}
				source = source.BaseType;
			}
		}
	}
}